from flask import request, jsonify, render_template
from control_publisher import send_control_command
import requests

def register_routes(app, socketio):

    # index
    @app.route('/')
    def index():
        return render_template('index.html')

    # 获取数据库中最新的120个数据，将其转换成json格式并返回
    @app.route('/history_data')
    def historical_data():
        from models import Data
        latest_data = Data.query.order_by(Data.timestamp.desc()).limit(120).all()
        data_list = [record.to_dict() for record in latest_data]
        return jsonify(data_list)

    # 历史数据界面
    @app.route('/history')
    def history():
        return render_template('history.html')

    # 获取温湿度，光照预测数据
    @app.route('/predict_data')
    def prediction_data():
        from prediction_model import load_data, get_or_train_models, predict_future
        # 加载历史数据
        df = load_data()
        if len(df) < 60:
            return jsonify({"error": "Not enough data to make predictions."}), 400
        try:
            results_temp, results_humidity, results_light = get_or_train_models(df)
            future_timestamps, predictions = predict_future(results_temp, results_humidity, results_light, steps=30)
            predicted_temps, predicted_humidities, predicted_light = zip(*predictions)
            predicted_temps = [round(float(temp), 1) for temp in predicted_temps]
            predicted_humidities = [round(float(humidity), 1) for humidity in predicted_humidities]
            predicted_light = [round(float(light), 1) for light in predicted_light]
            timestamps_str = [ts.strftime('%H:%M') for ts in future_timestamps]
            return jsonify({
                "timestamps": timestamps_str,
                "temperature": predicted_temps,
                "humidity": predicted_humidities,
                "light_intensity": predicted_light
            })
        except Exception as e:
            return jsonify({"error": str(e)}), 500

    # 预测界面
    @app.route('/predict')
    def predict():
        return render_template('predict.html')

    # 控制界面
    @app.route('/control')
    def control_page():
        return render_template('control.html')

    # 控制数据获取
    @app.route('/control_data', methods=['POST'])
    def control_device():
        try:
            data = request.get_json()
            device = data.get("device")
            command = data.get("command")
            if not device or command is None:
                return jsonify({"error": "缺少设备或命令"}), 400
            result = send_control_command(device, command)
            if result["status"] == "success":
                socketio.emit('device_status', {'device': device, 'status': command})
                return jsonify(result)
            else:
                return jsonify({"error": result["error"]}), 500
        except Exception as e:
            print(f"[错误] 处理控制命令时发生异常: {e}")
            return jsonify({"error": "处理请求时发生意外错误，请稍后重试"}), 500

    # 大模型界面
    @app.route('/chat')
    def chat():
        return render_template('chat.html')

    # 初始化大模型
    @app.route('/chat_data', methods=['POST'])
    def chat_data():
        data = request.get_json()
        user_message = data.get('message')
        city = data.get('city') or 'Tianjin'
        print(f"[LLM] 收到请求: {data}")

        if not user_message:
            return jsonify({'error': '缺少消息内容'}), 400

        from models import Data
        latest_data = Data.query.order_by(Data.timestamp.desc()).first()
        if not latest_data:
            return jsonify({'error': '暂无历史传感器数据'}), 400

        try:
            weather_response = requests.get(
                f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=9730e59aee8a58c027d787f612fceea5&units=metric&lang=zh_cn'
            )
            if weather_response.status_code != 200:
                weather_info = "无法获取天气信息"
            else:
                w_data = weather_response.json()
                weather_info = f"城市: {w_data['name']}, 温度: {w_data['main']['temp']}°C, 天气: {w_data['weather'][0]['description']}"

            context_prompt = f"""
你是一个专业的农业助手，请根据以下信息给出种植建议：
【实时传感器数据】
时间: {latest_data.timestamp.strftime('%Y-%m-%d %H:%M:%S')}
温度: {latest_data.temp}°C
湿度: {latest_data.humidity}%
光照强度: {latest_data.light} lux
【天气信息】
{weather_info}
【用户提问】
{user_message}
"""

            payload = {
                "model": "qwen3:1.7b",
                "prompt": context_prompt,
                "stream": False
            }

            OLLAMA_API_URL = 'http://127.0.0.1:11434/api/generate'
            response = requests.post(OLLAMA_API_URL, json=payload)
            if response.status_code != 200:
                return jsonify({'error': 'Ollama 返回错误', 'details': response.text}), 500

            ollama_data = response.json()
            return jsonify({
                'response': ollama_data.get('response', '无法获取回答'),
                'weather_info': weather_info,
                'sensor_data': {
                    'timestamp': latest_data.timestamp.strftime('%Y-%m-%d %H:%M:%S'),
                    'temp': latest_data.temp,
                    'humidity': latest_data.humidity,
                    'light': latest_data.light
                }
            })

        except Exception as e:
            print(f"[错误] 请求 Ollama 出错: {e}")
            return jsonify({'error': str(e)}), 500